package cn.dankal.flyaudio.friend;

import android.content.DialogInterface;
import android.content.Intent;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.StringUtils;
import com.classic.common.MultipleStatusView;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.kongzue.dialog.v2.SelectDialog;

import java.util.ArrayList;
import java.util.List;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import api.MyCardServiceFactory;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.base.recyclerview.OnRvItemClickListener;
import cn.dankal.basiclib.pojo.BaseResponse;
import cn.dankal.basiclib.rx.AbstractSubscriber;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.SharePreferenceManager;
import cn.dankal.basiclib.util.SimpleTextChange;
import cn.dankal.basiclib.util.SpannableStringUtils;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.widget.ClearEditText;
import cn.dankal.flyaudio.FlyApplication;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.adapter.FriendAdapter;
import cn.dankal.flyaudio.adapter.ShareFriendAdapter;
import cn.dankal.flyaudio.chat.ConversationListHelper;
import cn.dankal.flyaudio.configs.LiveDataBusConstant;
import cn.dankal.flyaudio.friend.utils.HandleResponseCode;
import cn.dankal.flyaudio.friend.utils.ShareUtils;
import cn.dankal.flyaudio.friend.utils.pinyin.HanziToPinyin;
import cn.dankal.flyaudio.pop.FriendSharePop;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.content.CustomContent;
import cn.jpush.im.android.api.content.ImageContent;
import cn.jpush.im.android.api.enums.ConversationType;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.android.api.options.MessageSendingOptions;
import cn.jpush.im.api.BasicCallback;

public class ChatShareActivity extends BaseActivity {

    private RecyclerView convList;
    private TextView rightText;
    private ShareFriendAdapter adapter;
    private ConversationListHelper controller = new ConversationListHelper();
    private String couponId;
    private String couponName="";
    private TextView searchTextView;

    private ClearEditText searchEditText;

    private MultipleStatusView statusView;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_chat_share;
    }

    @Override
    protected void initComponents() {
        findViewById(R.id.tv_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        couponId = getIntent().getStringExtra("couponId");
        couponName = getIntent().getStringExtra("couponName");
        rightText = findViewById(R.id.tv_right);
        convList = findViewById(R.id.recyclerview);
        adapter = new ShareFriendAdapter();
        adapter.setPickModel(FriendAdapter.PICK_MODEL_SINGLE);
        controller.initConvListAdapter();
        convList.setLayoutManager(new LinearLayoutManager(this));
        convList.setAdapter(adapter);

        initSearch();
        LiveEventBus.get("share", String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                finishActivity();
            }
        });
        findViewById(R.id.rl_create_new_conv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ChatShareActivity.this, CreateNewConvActivity.class);
                intent.putExtra("couponId", couponId);
                ActivityUtils.startActivity(intent);
            }
        });
        adapter.addDatas(controller.getConversations(), true);
        adapter.sortConvList();
        conversations.addAll(controller.getConversations());
        rightText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (adapter.getPickModel() == ShareFriendAdapter.PICK_MODEL_SINGLE) {
                    adapter.setPickModel(ShareFriendAdapter.PICK_MODEL_MORE);
                    rightText.setText("单选");
                } else if (adapter.getPickModel() == ShareFriendAdapter.PICK_MODEL_MORE) {
                    List<Conversation> conversations = adapter.getPickMembers();
                    if (conversations.isEmpty()) {
                        adapter.setPickModel(ShareFriendAdapter.PICK_MODEL_SINGLE);
                        rightText.setText("多选");
                    } else {
                        //发送
                        new FriendSharePop(ChatShareActivity.this)
                                .setConversation(conversations)
                                .setShareFile(ShareUtils.getInstance().getFile())
                                .setDoSendListener(new FriendSharePop.DoSendListener() {
                                    @Override
                                    public void doSend(String content) {
                                        ImageContent.createImageContentAsync(ShareUtils.getInstance().getFile(), new ImageContent.CreateImageContentCallback() {
                                            @Override
                                            public void gotResult(int responseCode, String responseMessage, ImageContent imageContent) {
                                                if (responseCode == 0) {
                                                    ToastUtils.showShort("发送成功");
                                                    for (Conversation conversation : conversations) {
                                                        imageContent.setStringExtra("jiguang", "xiong");
                                                        Message msg = conversation.createSendMessage(imageContent);
                                                        JMessageClient.sendMessage(msg);
                                                        if (!StringUtils.isEmpty(content)) {
                                                            conversation.createSendTextMessage(content);
                                                        }
                                                    }
                                                    finishActivity();
                                                } else {
                                                    ToastUtils.showShort(responseMessage);
                                                }
                                            }
                                        });
                                    }
                                })
                                .setPopupGravity(Gravity.CENTER)
                                .showPopupWindow(findViewById(android.R.id.content));
                    }

                }
            }
        });
        LiveEventBus.get(LiveDataBusConstant.UPDATE_SHARE_MEMBERS, String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                List<Conversation> conversations = adapter.getPickMembers();
                if (conversations.isEmpty()) {
                    rightText.setText("单选");
                } else {
                    rightText.setText("发送(" + conversations.size() + ")");
                }
            }
        });
        if (!StringUtils.isEmpty(couponId)) {
            rightText.setVisibility(View.GONE);
            adapter.setOnRvItemClickListener(new OnRvItemClickListener<Conversation>() {
                @Override
                public void onItemClick(View v, int position, Conversation data) {
                    SelectDialog.show(ChatShareActivity.this, "提示", "是否赠送此优惠券!", "确定", (dialog, which) -> {
                        ConversationType convType = data.getType();
                        Conversation conv = null;
                        if (convType != null) {
                            switch (convType) {
                                case single:
                                    doSendReq(couponId, ((UserInfo) data.getTargetInfo()).getUserName(), data);
                                    break;
                                case group:
                                    doSendReqByGroup(couponId, ((GroupInfo) data.getTargetInfo()).getGroupID() + "", data);
                                    break;
                                case chatroom:
                                    break;
                                default:
                            }
                        }
                    }, "取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

                }
            });
        } else {
            adapter.setOnRvItemClickListener(new OnRvItemClickListener<Conversation>() {
                @Override
                public void onItemClick(View v, int position, Conversation data) {
                    ConversationType convType = data.getType();
                    Conversation conv = null;
                    if (convType != null) {
                        switch (convType) {
                            case single:
                                new FriendSharePop(ChatShareActivity.this)
                                        .setTargetId(((UserInfo) data.getTargetInfo()).getUserName())
                                        .setShareFile(ShareUtils.getInstance().getFile())
                                        .setDoSendListener(new FriendSharePop.DoSendListener() {
                                            @Override
                                            public void doSend(String content) {
                                                ImageContent.createImageContentAsync(ShareUtils.getInstance().getFile(), new ImageContent.CreateImageContentCallback() {
                                                    @Override
                                                    public void gotResult(int responseCode, String responseMessage, ImageContent imageContent) {
                                                        if (responseCode == 0) {
//                                                            imageContent.setStringExtra("jiguang", "xiong");
                                                            Message msg = data.createSendMessage(imageContent);
                                                            JMessageClient.sendMessage(msg);
                                                            if (!StringUtils.isEmpty(content)) {
                                                                data.createSendTextMessage(content);
                                                            }
                                                            toChatBySingle(data.getTitle(),
                                                                    ((UserInfo) data.getTargetInfo()).getUserName(),msg);
                                                            finishActivity();
                                                        } else {
                                                            ToastUtils.showShort(responseMessage);
                                                        }
                                                    }
                                                });
                                            }
                                        })
                                        .setPopupGravity(Gravity.CENTER)
                                        .showPopupWindow(findViewById(android.R.id.content));
                                break;
                            case group:
                                new FriendSharePop(ChatShareActivity.this)
                                        .setGroupId(((GroupInfo) data.getTargetInfo()).getGroupID())
                                        .setShareFile(ShareUtils.getInstance().getFile())
                                        .setDoSendListener(new FriendSharePop.DoSendListener() {
                                            @Override
                                            public void doSend(String content) {
                                                toChatByGroupWithMessage(content,data.getTitle(),(((GroupInfo) data.getTargetInfo()).getGroupID()));
                                                finishActivity();

                                                /*ImageContent.createImageContentAsync(ShareUtils.getInstance().getFile(), new ImageContent.CreateImageContentCallback() {
                                                    @Override
                                                    public void gotResult(int responseCode, String responseMessage, ImageContent imageContent) {
                                                        if (responseCode == 0) {
//                                                            imageContent.setStringExtra("jiguang", "xiong");
                                                            MessageSendingOptions options = new MessageSendingOptions();
                                                            options.setNeedReadReceipt(true);
                                                            Message msg = data.createSendMessage(imageContent);
                                                            JMessageClient.sendMessage(msg,options);
                                                            if (!StringUtils.isEmpty(content)) {
                                                                Message message = data.createSendTextMessage(content);
                                                                JMessageClient.sendMessage(message,options);
                                                            }
                                                            toChatByGroup(data.getTitle(), ((GroupInfo) data.getTargetInfo()).getGroupID());
                                                            finishActivity();
                                                        } else {
                                                            ToastUtils.showShort(responseMessage);
                                                        }
                                                    }
                                                });*/
                                            }
                                        })
                                        .setPopupGravity(Gravity.CENTER)
                                        .showPopupWindow(findViewById(android.R.id.content));
                                break;
                            case chatroom:
                                break;
                            default:
                        }
                    }
                }
            });
        }
    }

    private void send(String transferOrderUuid, Conversation conversation) {
        CustomContent customContent = new CustomContent();
        customContent.setStringExtra("coupon_id", transferOrderUuid);
        customContent.setStringExtra("sendCoupon", "sendCoupon");
        customContent.setStringExtra("couponName", couponName);
        Message textMessage = conversation.createSendMessage(customContent);
        MessageSendingOptions options = new MessageSendingOptions();
        options.setNeedReadReceipt(true);
        JMessageClient.sendMessage(textMessage, options);
        textMessage.setOnSendCompleteCallback(new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                if (i == 0) {
                    SharePreferenceManager.setIsOpen(true);
                    Toast.makeText(ChatShareActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                    ConversationType convType = conversation.getType();
                    if (convType != null) {
                        switch (convType) {
                            case single:
                                toChatBySingle(conversation.getTitle(),
                                        ((UserInfo) conversation.getTargetInfo()).getUserName(),textMessage);
                                break;
                            case group:
                                toChatByGroup(conversation.getTitle(),
                                        ((GroupInfo) conversation.getTargetInfo()).getGroupID(),textMessage);
                                break;
                            case chatroom:

                                break;
                            default:
                        }
                    }
                    finish();
                } else {
                    HandleResponseCode.onHandle(ChatShareActivity.this, i, false);
                }
            }
        });
    }

    private void toChatBySingle(String title, String username,Message textMessage) {
        Intent intent = new Intent(this, ChatActivity.class);
        intent.putExtra(FlyApplication.MSG_JSON, textMessage.toJson());
        intent.putExtra(FlyApplication.CONV_TITLE, "");
        intent.putExtra(FlyApplication.TARGET_ID, username);
        startActivity(intent);
    }

    private void toChatByGroup(String title, long groupId,Message textMessage) {
        Intent intent = new Intent(this, ChatActivity.class);
        intent.putExtra(FlyApplication.CONV_TITLE, title);
        intent.putExtra(FlyApplication.MSG_JSON, textMessage.toJson());
        intent.putExtra(FlyApplication.GROUP_ID, groupId);
        startActivity(intent);
    }

    private void toChatByGroupWithMessage(String text,String title, long groupId) {
        Intent intent = new Intent(this, ChatActivity.class);
        intent.putExtra(FlyApplication.CONV_TITLE, title);
        intent.putExtra(FlyApplication.GROUP_ID, groupId);
        intent.putExtra(FlyApplication.MESSAGE_SHARE_MSG,true);
        intent.putExtra(FlyApplication.MESSAGE_TEXT,text);
        startActivity(intent);
    }


    private void doSendReqByGroup(String couponId, String groupId, Conversation conversation) {
        showLoadingDialog();
        MyCardServiceFactory.couponsExchangeByGroup(couponId, groupId)
                .subscribe(new AbstractSubscriber<BaseResponse<String>>(this) {
                    @Override
                    public void onNext(BaseResponse<String> objectBaseResponse) {
                        dismissLoadingDialog();
                        ToastUtils.showShort("发送成功");
                        send(objectBaseResponse.getData(), conversation);
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        super.onError(e);
                    }
                });
    }

    private List<Conversation> conversations = new ArrayList<>();

    private void initSearch() {
        statusView = findViewById(R.id.multiple_status_view);
        searchTextView = findViewById(R.id.tv_search);
        searchEditText = findViewById(R.id.et_search);
        searchEditText.setOnSearchListener(new ClearEditText.OnSearchListener() {
            @Override
            public void doSearch(String keyword) {
                if (TextUtils.isEmpty(keyword)) return;
                mDoSearch(keyword);
            }
        });
        searchTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key = searchEditText.getText().toString();
                if (TextUtils.isEmpty(key)) return;
                mDoSearch(key);
            }
        });
        searchEditText.addTextChangedListener(new SimpleTextChange() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
                if (TextUtils.isEmpty(s)) {
                    statusView.showContent();
                    adapter.addDatas(conversations, true);
                }
            }
        });
        statusView.showContent();
    }

    private void mDoSearch(String key) {
        List<Conversation> searResult = new ArrayList<>();
        for (Conversation conversation : conversations) {
            ArrayList<HanziToPinyin.Token> tokens = HanziToPinyin.getInstance()
                    .get(conversation.getTitle());
            StringBuilder sb = new StringBuilder();
            if (tokens != null && tokens.size() > 0) {
                for (HanziToPinyin.Token token : tokens) {
                    if (token.type == HanziToPinyin.Token.PINYIN) {
                        sb.append(token.target);
                    } else {
                        sb.append(token.source);
                    }
                }
            }
            if (sb.toString().contains(key) || conversation.getTitle().contains(key)) {
                searResult.add(conversation);
            }
        }
        if (searResult.isEmpty()) {
            SpannableStringBuilder s =
                    SpannableStringUtils.getBuilder(key).setForegroundColor(getResources().getColor(R.color.color_0085B4)).create();

            statusView.showEmpty("- 没有找到“" + s + "”相关结果 -");

        } else {
            statusView.showContent();
            adapter.addDatas(searResult, true);
//            adapter.setNewData(searResult, true);
//            friendView.setAdapter(searchUserAdapter);
        }
    }

    private void doSendReq(String couponId, String userId, Conversation conversation) {
        showLoadingDialog();
        MyCardServiceFactory.couponsExchange(couponId, userId)
                .subscribe(new AbstractSubscriber<BaseResponse<String>>(this) {
                    @Override
                    public void onNext(BaseResponse<String> objectBaseResponse) {
                        dismissLoadingDialog();
                        ToastUtils.showShort("发送成功");
                        send(objectBaseResponse.getData(), conversation);
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        super.onError(e);
                    }
                });
    }
}
